package com.dc.datacollect.components.upload;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
 * 文件上传服务
 *
 * @author zhuangjie
 * @date 2023/05/13
 */
@Component
@Slf4j
public class FileUploadService {
    /**
     * 网站统一前缀（默认就是""空字符串）
     */
    @Value("${server.servlet.context-path:}")
    private String appPrefix;

    @Value("${component-service.upload.store-vest:}")
    private String storeVest;

    @Value("${component-service.upload.request-vest:}")
    private String requestVest;

    @Autowired
    private FileResponseServerController fileResponseServerController;



    public String MultipartFileToUrl(MultipartFile file,String customFilePrefixName) throws Exception {
        try {
            if (file != null) {
                // 原始名称
                String originalFilename = file.getOriginalFilename();
                // 扩展名
                String ext = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
                String filePrefixName = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
                if (customFilePrefixName != null ) {
                    filePrefixName = customFilePrefixName;
                }
                String fullFileName = filePrefixName + ext;
                // 存储,要存储到指定的文件夹，/uploads/yyyy-MM-dd，考虑文件过多的情况按照日期，生成一个子文件夹
                String childFolder = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
                File folder = new File(storeVest+"/"+childFolder);
                // 确保目录存在
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                // 存储文件到目录
                file.transferTo(new File(folder, fullFileName));
                // 存放在数据库中的url
                return appPrefix+requestVest+("/" + childFolder+"/"+fullFileName);
            }
        } catch (Exception e) {
            log.error("ERROR 上传失败：{}",e.getMessage());
        }
        throw new Exception("上传失败");
    }

    public String MultipartFileToUrl(MultipartFile file) throws Exception {
        return MultipartFileToUrl(file,null);
    }

    public UploadFileWrap createUploadFileWrap(String relDir,String filename) {
        String preUrl = (requestVest + "/" + relDir + "/" + filename).replaceAll("/+", "/");
        UploadFileWrap uploadFileWrap = new UploadFileWrap();
        uploadFileWrap.setUrl(preUrl);
        File file = fileResponseServerController.urlToFile(preUrl);
        // 获取父级目录
        File parentDir = file.getParentFile();
        // 检查父级目录是否存在，如果不存在则创建
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
        uploadFileWrap.setFile(file);
        return uploadFileWrap;
    }
}
